package com.xxx.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xxx.common.Const;
import com.xxx.common.dto.JsonResult;
import com.xxx.common.dto.Page;
import com.xxx.common.dto.Pagination;
import com.xxx.common.dto.ZtreeNode;
import com.xxx.common.utils.ErrorUtil;
import com.xxx.common.utils.RegexValidateUtil;
import com.xxx.common.utils.StrUtil;
import com.xxx.model.SysRole;
import com.xxx.model.SysUserBasis;
import com.xxx.model.SysUserRole;
import com.xxx.service.SysRoleService;
import com.xxx.service.SysUserBasisService;
import com.xxx.service.SysUserRoleService;

@Controller
@RequestMapping("sys/user/*")
public class SysUserBasisController {
	
	@Autowired
	private SysUserBasisService sysUserBasisService;
	
	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Autowired
	private SysRoleService sysRoleService;
	
	/**
	 * 列表 页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "index.html", method = RequestMethod.GET)
	public ModelAndView index(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/user/index");
		int currentPage = NumberUtils.toInt(request.getParameter("page"), 1);
		String search = request.getParameter("search");	//搜索
		Map<String, Object> whereMap = new HashMap<>();
		if(StrUtil.notEmpty(search)){
			if(RegexValidateUtil.isPhone(search)){
				whereMap.put("phone", search);		
			}else{
				whereMap.put("username", search);
			}
			mv.addObject("search", search);
		}
		Page<SysUserBasis> page = sysUserBasisService.getPage(whereMap, new Pagination(currentPage));
		mv.addObject("page", page);
		return mv;
	}
	
	/**
	 * 添加/修改 页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "create.html", method = RequestMethod.GET)
	public ModelAndView create(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/user/create");
		long id = NumberUtils.toLong(request.getParameter("id"), Const.DEFAULT_LONG_NULL);
		if(id != Const.DEFAULT_LONG_NULL){
			SysUserBasis sysUserBasis = sysUserBasisService.getEntity(id);
			mv.addObject("data", sysUserBasis);
		}
		mv.addObject("sexlist", Const.getStatusList("女 "," 男"));
		mv.addObject("statuslist", Const.getStatusList("停用","启用"));
		return mv;
	}
	
	/**
	 * 保存/修改
	 * @param SysUserBasis
	 * @param result
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult save(@Valid SysUserBasis sysUserBasis, BindingResult result) throws Exception {
		if (result.hasErrors()) {
			return ErrorUtil.getError(result);
		}
		SysUserBasis user = sysUserBasisService.getEntityByPhone(sysUserBasis.getPhone());
		if(user.getId() != null && (sysUserBasis.getId() == null || !sysUserBasis.getId().equals(user.getId()))){
			return JsonResult.build(-1, "手机号码不能重复！");
		}
		user = sysUserBasisService.getEntityByLoginCode(sysUserBasis.getLogincode());
		if(user.getId() != null && (sysUserBasis.getId() == null || !sysUserBasis.getId().equals(user.getId()))){
			return JsonResult.build(-1, "用户编号【"+sysUserBasis.getLogincode()+"】已存在！");
		}
		long ret = sysUserBasisService.saveOrUpdate(sysUserBasis);
		if(ret > 0){
			return JsonResult.ok();
		}
		return JsonResult.build(-1, "保存失败!");
	}
	
	/**
	 * 删除
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "delete", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult delete(HttpServletRequest request) throws Exception {
		String[] ids = request.getParameterValues("checkedid");
		if(ids == null || ids.length == 0){
			return JsonResult.build(-1, "请选择要删除的记录!");
		}
		for (String id : ids) {
			sysUserBasisService.delete(NumberUtils.toLong(id));
		}
		return JsonResult.ok();
	}
	
	/**
	 * 用户管理页面
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "manage.html", method = RequestMethod.GET)
	public ModelAndView manage(HttpServletRequest request) throws Exception{
		ModelAndView mv = new ModelAndView("sys/user/manage");
		long id = NumberUtils.toLong(request.getParameter("id"), Const.DEFAULT_LONG_NULL);
		if(id != Const.DEFAULT_LONG_NULL){
			SysUserBasis sysUserBasis = sysUserBasisService.getEntity(id);
			mv.addObject("data", sysUserBasis);
		}
		return mv;
	}
	
	/**
	 * 重置密码
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "resetpwd", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult resetPwd(HttpServletRequest request) throws Exception {
		long id = NumberUtils.toLong(request.getParameter("id"), Const.DEFAULT_LONG_NULL);
		String pwd = request.getParameter("pwd");
		if(id != Const.DEFAULT_LONG_NULL && StrUtil.notEmpty(pwd)){
			boolean ret = sysUserBasisService.resetPwd(id, pwd);
			if(ret){
				return JsonResult.ok();
			}
		}
		return JsonResult.build(-1, "保存失败!");
	}
	
	/**
	 * 角色授权 树
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "user_grant",method = {RequestMethod.POST},produces="application/json;charset=UTF-8")
	public JsonResult userGrant(HttpServletRequest request) throws Exception{
		long userid = NumberUtils.toLong(request.getParameter("userid"), Const.DEFAULT_LONG_NULL);	//用户id
		if(userid != Const.DEFAULT_LONG_NULL){
			Map<Long, Long> roleUserMap = sysUserRoleService.getUserRoleMap(userid);
			Map<String, Object> whereMap = new HashMap<>();
			whereMap.put("status", 1);		//启用的角色
			List<SysRole> roleList = sysRoleService.getList(whereMap);
			List<ZtreeNode> nodeList = new ArrayList<>();
			ZtreeNode node = null;
			for (SysRole role : roleList) {
				node = new ZtreeNode(role.getId().toString(), role.getRolename(), roleUserMap.containsKey(role.getId()));
				nodeList.add(node);
			}
			return JsonResult.ok(nodeList);
		}
		return JsonResult.build(-1, "参数错误！");
	}
	
	/**
	 * 角色授权
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "role_grant_save", produces = "application/json;charset=UTF-8", method = RequestMethod.POST)
	public JsonResult roleGrantSave(HttpServletRequest request) throws Exception {
		long userid = NumberUtils.toLong(request.getParameter("userid"), Const.DEFAULT_LONG_NULL);	//角色id
		String[] ids = request.getParameterValues("ids[]");
		Map<Long,Long> roleUserMap = sysUserRoleService.getUserRoleMap(userid);
		if(ids != null){
			SysUserRole roleuser = null;
			for (String strid : ids) {
				long roleid = NumberUtils.toLong(strid);
				if(roleUserMap.containsKey(roleid)){
					roleUserMap.remove(roleid);
				}else{
					roleuser = new SysUserRole(roleid, userid);
					sysUserRoleService.saveOrUpdate(roleuser);	 //添加授权
				}
			}
		}
		if(!roleUserMap.isEmpty()){
			for (Long id : roleUserMap.values()) {
				sysUserRoleService.delete(id);					 //取消授权
			}
		}
		return  JsonResult.ok();
	}
}
